<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
        <title>AJ Utils-RsaCrypto</title>
        <meta name="description" content="Small Java utilities with many useful functions. RsaCrypto" />
        <meta name="keywords" content="AJ Utils, ajaxjs, ajaxjs framework, java utilities, tools, helper, RsaCrypto" />
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <link rel="stylesheet" href="https://framework.ajaxjs.com/static/new-ui/css/common.css" />
        <link rel="stylesheet" href="https://iam.ajaxjs.com/asset/main.css"/>
        <link rel="icon" type="image/x-icon" href="https://framework.ajaxjs.com/aj-logo/logo.ico"/>
        <script src="https://framework.ajaxjs.com/static/aj-docs/common.js"></script>
        <script>
            // 获取用户的默认语言
            var userLang = navigator.language || navigator.userLanguage;

            // 检查是否为中文环境（包括简体和繁体）
            if (userLang.startsWith('zh') && location.pathname.indexOf('cn') == -1) {
                 confirm('欢迎！您可以改为访问中文内容。是否继续？') && location.assign('/cn');  // 如果是中文，则弹出提示
            }

            var _hmt = _hmt || [];
            (function() {
              var hm = document.createElement("script");
              hm.src = "https://hm.baidu.com/hm.js?208c5aea11c52991bd1c3283e62ad0ce";
              var s = document.getElementsByTagName("script")[0];
              s.parentNode.insertBefore(hm, s);
            })();
        </script>
    </head>
    <body>
        <nav>
            <div>
                <div class="links">
                    <a href="/">🏠 Home</a>
                    | ⚙️ Source:
                    <a target="_blank" href="https://github.com/lightweight-component/aj-util">Github</a>/<a target="_blank" href="https://gitcode.com/lightweight-component/aj-util">Gitcode</a>
                    | 🚀 <a href="/cn">Chinese Version</a>
                </div>
                <h1>
                    <img src="https://framework.ajaxjs.com/aj-logo/logo.png" style="vertical-align: middle;height: 45px;margin-bottom: 6px;" />
                    AJ Utils
                </h1>
                <h3>Small Java Utils Library</h3>
            </div>
        </nav>
        <div>
            <menu>
                
                <ul>
                    <li class="selected">
                        <a href="/">Home</a>
                    </li>
                </ul>
                <h3>Common</h3>
                <ul>
                    <li><a href="/common/JsonUtil/">JsonUtil</a></li>
                    <li><a href="/common/BytesHelper/">BytesHelper</a></li>
                    <li><a href="/common/ConvertBasicValue/">ConvertBasicValue</a></li>
                    <li><a href="/common/MessageDigestHelper/">HashHelper</a></li>
                    <li><a href="/common/MapTool/">MapTool</a></li>
                    <li><a href="/common/ObjectHelper/">ObjectHelper</a></li>
                    <li><a href="/common/RandomTools/">RandomTools</a></li>
                    <li><a href="/common/RegExpUtils/">RegExpUtils</a></li>
                    <li><a href="/common/StrUtil/">StrUtil</a></li>
                    <li><a href="/common/BoxLogger/">BoxLogger</a></li>
                    <li><a href="/common/BytesHelper/">BytesHelper</a></li>
                    <li><a href="/common/EncodeTools/">UrlEncode</a></li>
                    <li><a href="/common/XmlHelper/">XmlHelper</a></li>
                    <li><a href="/common/WebUtils/">WebUtils</a></li>
                </ul>
                <h3>Date Handing</h3>
                <ul>
                    <li><a href="/date/intro/">Introduction</a></li>
                    <li><a href="/date/convert/">Date Converter</a></li>
                    <li><a href="/date/formatter/">Date Formatter</a></li>
                </ul>
                <h3>Reflection</h3>
                <ul>
                    <li><a href="/reflect/Methods/">Methods</a></li>
                    <li><a href="/reflect/Types/">Types</a></li>
                    <li><a href="/reflect/Clazz/">Clazz</a></li>
                </ul>

                <h3>IO</h3>
                <ul>
                    <li><a href="/io/FileHelper/">FileHelper</a></li>
                    <li><a href="/io/Resources/">Resources</a></li>
                    <li><a href="/io/StreamHelper/">DataReader/DataWriter</a></li>
                    <li><a href="/io/ZipHelper/">ZipHelper</a></li>
                </ul>

                <h3>HTTP Request</h3>
                <ul>
                    <li><a href="/http_request/Get">HTTP Request</a></li>
                    <li><a href="/http_request/advanced-usage/">Advanced Usage</a></li>
                    <li><a href="/http_request/Base/">Base</a></li>
                </ul>
    
               <h3>Cryptography</h3>
               <ul>
                <li><a href="/cryptography/intro/">Introduction</a></li>
                <li><a href="/cryptography/flow/">Basic Flow</a></li>
                <li><a href="/cryptography/AesCrypto/">AES/DES</a></li>
                <li><a href="/cryptography/RsaCrypto/">RSA</a></li>
               </ul>
            </menu>
            <article class="aj-text">
                <h1>RSA Encryption and Decryption</h1>
<p>RSA asymmetric encryption involves many tasks, which can be decomposed into the following sub-tasks:</p>
<ul>
<li>Signing, encapsulated in <code>com.ajaxjs.util.cryptography.rsa.DoSignature</code></li>
<li>Signature verification, encapsulated in <code>com.ajaxjs.util.cryptography.rsa.DoVerify</code></li>
<li>Key management, encapsulated in <code>com.ajaxjs.util.cryptography.rsa.KeyMgr</code></li>
<li>RSA encryption and decryption itself</li>
</ul>
<p>Each will be introduced separately below.</p>
<h2>Signing</h2>
<p>Input parameters include algorithm, input data, and private key. Execute <code>sign()</code> to return the signature. The involved types are as follows:</p>
<ul>
<li>Input data, can be <code>byte[]</code> or string</li>
<li>Private key, can be a PrivateKey object or string. If it's a string, it will be restored to a PrivateKey object through <code>KeyMgr.restoreKey</code></li>
<li>The returned signature data is <code>byte[]</code>, and <code>signToString()</code> can be called to return a base64-encoded string</li>
</ul>
<pre><code class="language-java">// Generate public and private keys
KeyMgr keyMgr = new KeyMgr(Constant.RSA, 1024);
keyMgr.generateKeyPair();
String privateKey = keyMgr.getPrivateKeyStr();

byte[] helloWorlds = new DoSignature(Constant.SHA256_RSA).setStrData(&quot;hello world&quot;).setPrivateKeyStr(privateKey).sign();
String result = new DoSignature(Constant.SHA256_RSA).setStrData(&quot;hello world&quot;).setPrivateKeyStr(privateKey).signToString();

assertEquals(EncodeTools.base64EncodeToString(helloWorlds), result);
</code></pre>
<p>It's worth mentioning that where does the private key come from? You can generate it through the above KeyMgr.</p>
<h2>Signature Verification</h2>
<p>Input parameters include algorithm, input data, signature data, and public key. Execute <code>verify()</code> to verify the signature. The involved types are as follows:</p>
<ul>
<li>Input data, can be <code>byte[]</code> or string</li>
<li>Signature data, can be <code>byte[]</code> or Base64 string</li>
<li>Public key, can be a PublicKey object or string. If it's a string, it will be restored to a PublicKey object through <code>KeyMgr</code></li>
<li>Whether the returned signature is valid, is <code>boolean</code></li>
</ul>
<pre><code class="language-java">// Generate public and private keys
KeyMgr keyMgr = new KeyMgr(Constant.RSA, 1024);
keyMgr.generateKeyPair();
String publicKey = keyMgr.getPublicKeyStr(), privateKey = keyMgr.getPrivateKeyStr();
String result = new DoSignature(Constant.SHA256_RSA).setStrData(&quot;hello world&quot;).setPrivateKeyStr(privateKey).signToString();
boolean verified = new DoVerify(Constant.SHA256_RSA).setStrData(&quot;hello world&quot;).setPublicKeyStr(publicKey).setSignatureBase64(result).verify();

assertTrue(verified);
</code></pre>
<p>It's worth mentioning that where do the public and private keys come from? You can generate them through the above <code>KeyMgr</code>.</p>
<h2>RSA Encryption and Decryption</h2>
<p>Nothing more to say, directly show the API examples.</p>
<pre><code class="language-java">// Generate public and private keys
KeyMgr keyMgr = new KeyMgr(Constant.RSA, 1024);
keyMgr.generateKeyPair();
String publicKey = keyMgr.getPublicKeyStr(), privateKey = keyMgr.getPrivateKeyStr();

System.out.println(&quot;Public Key: \n\r&quot; + publicKey);
System.out.println(&quot;Private Key: \n\r&quot; + privateKey);
//		System.out.println(&quot;Public Key Encryption--------Private Key Decryption&quot;);

String word = &quot;你好，世界！&quot;;

byte[] encWord = KeyMgr.publicKeyEncrypt(word.getBytes(), publicKey);
String decWord = new String(KeyMgr.privateKeyDecrypt(encWord, privateKey));

String eBody = EncodeTools.base64EncodeToString(encWord);
String decWord2 = new String(KeyMgr.privateKeyDecrypt(EncodeTools.base64Decode(eBody), privateKey));
System.out.println(&quot;Before Encryption: &quot; + word + &quot;\n\rCiphertext: &quot; + eBody + &quot;\nAfter Decryption: &quot; + decWord2);
assertEquals(word, decWord);

//		System.out.println(&quot;Private Key Encryption--------Public Key Decryption&quot;);

String english = &quot;Hello, World!&quot;;
byte[] encEnglish = KeyMgr.privateKeyEncrypt(english.getBytes(), privateKey);
String decEnglish = new String(KeyMgr.publicKeyDecrypt(encEnglish, publicKey));
//		System.out.println(&quot;Before Encryption: &quot; + english + &quot;\n\r&quot; + &quot;After Decryption: &quot; + decEnglish);

assertEquals(english, decEnglish);
//		System.out.println(&quot;Private Key Signing——Public Key Signature Verification&quot;);

// Generate signature
String sign = new DoSignature(Constant.MD5_RSA).setPrivateKeyStr(privateKey).setData(encEnglish).signToString();
//		System.out.println(&quot;Signature:\r&quot; + sign);
// Verify signature
assertTrue(new DoVerify(Constant.MD5_RSA).setPublicKeyStr(publicKey).setData(encEnglish).setSignatureBase64(sign).verify());
</code></pre>
<h2>Key Management</h2>
<p>Some utility methods for keys are in <code>KeyMgr</code>, including both public and private keys. Generally, open-source projects like to encapsulate <code>KeyPair</code> as a Map, but the author thinks using <code>KeyPair</code> itself is sufficient. If not fully satisfied, certain methods can be added, such as <code>getPublicKeyBytes()</code>, <code>getPublicKeyStr()</code>, <code>getPublicToPem()</code>, which are clearer compared to using Map.</p>
<p>Additionally, the keys themselves can also be encrypted and decrypted for higher security.</p>

            </article>
        </div>

       <footer>
            AJ-Util, a part of <a href="https://framework.ajaxjs.com" target="_blank">AJ-Framework</a> open source. Mail:
            frank@ajaxjs.com, visit <a href="https://blog.csdn.net/zhangxin09" target="_blank">my blog(In Chinese)</a>.
            <br />
            <br />
            Copyright © 2025 Frank Cheung. All rights reserved.
        </footer>
    </body>
</html>